#include <REGX52.h>
#include "Timer.h"
#include "SoleKey.h"
#include "AT24C02.h"
#include "Nixie.h"
#include "Delay.h"


unsigned char KeyNum = 0;
unsigned char Min, Sec, MinSec;
unsigned char StartFlag = 0;

void main()
{
	Timer0_Init();
    while(1)
    {
        KeyNum = Key();
		if(KeyNum == 1)
		{
			StartFlag = !StartFlag;//开始/暂停计时
		}
		if(KeyNum == 2)
		{
			Min = 0, Sec = 0, MinSec = 0;//清零
		}
		if(KeyNum == 3)//记录秒表
		{
			AT24C02_WriteByte(0, Min);
			Delayms(5);
			AT24C02_WriteByte(1, Sec);
			Delayms(5);
			AT24C02_WriteByte(2, MinSec);
			Delayms(5);
		}
		if(KeyNum == 4)//读出存储的秒表信息数据
		{
			Min = AT24C02_ReadByte(0);
			Sec = AT24C02_ReadByte(1);
			MinSec = AT24C02_ReadByte(2);
		}	
		Nixie_SetBuff(1, Min / 10);
		Nixie_SetBuff(2, Min % 10);
		Nixie_SetBuff(3, 11);
		Nixie_SetBuff(4, Sec / 10);
		Nixie_SetBuff(5, Sec % 10);
		Nixie_SetBuff(6, 11);
		Nixie_SetBuff(7, MinSec / 10);
		Nixie_SetBuff(8, MinSec % 10);
    }
}

//秒表逻辑
void Sec_Looper()
{
	if(StartFlag)
	{
		MinSec++;
		if(MinSec >= 100)
		{
			MinSec = 0;
			Sec++;
			if(Sec >= 60)
			{
				Sec = 0;
				Min++;
				if(Min >= 60)
					Min = 0;
			}
		}
	}
	
}

//定时器0中断函数模板——每1ms中断一次
void Timer0_Rountine(void) interrupt 1
{
	//独立按键计时，数码管计时，秒表计时
	static unsigned char KeyCount = 0, NixieCount = 0, SecCount;
	TH0 = 64535 / 256;		//高8位
	TL0 = 64535 % 256 + 1;		//低8位
	KeyCount++, NixieCount++, SecCount++;
	if(KeyCount >= 20)//独立按键每20ms检测一次
	{
		KeyCount = 0;
		SoleKey_Looper();
	}
	if(NixieCount >= 2)//数码管每2ms扫描一次
	{
		NixieCount = 0;
		Nixie_Looper();
	}
	if(SecCount >= 10)//秒表每10ms加1
	{
		SecCount = 0;
		Sec_Looper();
	}
}